package org.jsola.hr.web;

import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.HrCustomerDetailsAddDTO;
import org.jsola.hr.service.IHrCustomerDetailsService;
import org.jsola.salary.entity.CustomerDetailsDO;
import org.jsola.salary.vo.CustomerDetailsVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 客户明细表
 *
 * @author JanusMix
 */
@RestController("hrHrCustomerDetailsController")
@RequestMapping(HrConstants.API_PATH + "/v1/customerDetails")
public class HrCustomerDetailsController implements IHrCustomerDetailsControllerAPI {

    @Autowired
    private IHrCustomerDetailsService hrCustomerDetailsService;


    @Override
    @PostMapping("/saveByCompanyIds")
    public Result<List<CustomerDetailsVO>> saveByCompanyIds(@Valid @RequestBody HrCustomerDetailsAddDTO hrCustomerDetailsAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增客户明细表权限校验

        List<CustomerDetailsDO> customerDetailsDOList = hrCustomerDetailsService
                .saveByCompanyIds(hrCustomerDetailsAddDTO, tokenUser);
        ParamException.notEmpty(customerDetailsDOList, "新增客户明细失败，请刷新后重试");

        return Result.success(
                customerDetailsDOList.parallelStream().map(customerDetailsDO
                        -> customerDetailsDO.to(CustomerDetailsVO.class)).collect(Collectors.toList())
        );
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody Long[] customerDetailsIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除客户明细表权限校验

        int count = hrCustomerDetailsService.deleteByIds(tokenUser, customerDetailsIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping("/selectLastOne")
    public Result<CustomerDetailsDO> selectLastOne() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除客户明细表权限校验

        return Result.success(
                hrCustomerDetailsService.selectLastOne(tokenUser)
        );
    }

}